using System.Reflection;
using System.Xml;

namespace XmlObjects
{
	public class BasicXmlElementPropertyReader : AttributePropertyReader
	{
		public new static bool IsMyType(PropertyInfo propertyInfo)
		{
			return GetAttribute<XmlElementAttribute>(propertyInfo) != null && CanHandleDataType(propertyInfo);
		}

		private XmlElementAttribute attribute;

		public BasicXmlElementPropertyReader(PropertyInfo propertyInfo)
		{
			attribute = GetAttribute<XmlElementAttribute>(propertyInfo);
			this.propertyInfo = propertyInfo;
		}


		public override void WriteXml(XmlNode node, DocumentElement theObject, XmlDocument ownerDocument)
		{
			XmlNode elementNode = node.SelectSingleNode(attribute.Name);
			if (elementNode==null)
			{
				elementNode = ownerDocument.CreateElement(attribute.Name);
				node.AppendChild(elementNode);
			}
			elementNode.InnerText = propertyInfo.GetValue(theObject, null).ToString();
		}

		public override void ReadXml(XmlNode node, object theObject)
		{
			XmlNode elementNode = node.SelectSingleNode(attribute.Name);
			string theValue;
			if (elementNode!=null)
				theValue = elementNode.InnerText;
			else
				theValue = null;
			propertyInfo.SetValue(theObject, GetTheValue(theValue), null);
		}
	}
}